package com.team7.happycommunity.businessservice.controller;

import com.team7.happycommunity.businessservice.common.CommonResult;
import com.team7.happycommunity.businessservice.common.LoginToken;
import com.team7.happycommunity.businessservice.entity.*;
import com.team7.happycommunity.businessservice.exception.LoginException;
import com.team7.happycommunity.businessservice.exception.MailboxStatusException;
import com.team7.happycommunity.businessservice.service.AreainfoService;
import com.team7.happycommunity.businessservice.service.BusinessInfoService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * (BusinessInfo)表控制层
 *
 * @author makejava
 * @since 2020-03-25 20:07:27
 */
@RestController
@RequestMapping("businessInfo")
@Api(tags="商家信息管理接口")
public class BusinessInfoController {
    /**
     * 服务对象
     */
    @Resource
    private BusinessInfoService businessInfoService;
    /**
     * 小区信息
     */
    @Resource
    private AreainfoService areainfoService;

    @Autowired
    private HttpServletRequest request;
    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public BusinessInfo selectOne(Integer id) {
        return this.businessInfoService.queryById(id);
    }
    /**
     *
     * @param text 登录的手机号或者邮箱
     * @param password 密码
     * @return
     */
    @RequestMapping("/subLogin")
    @ResponseBody
    @ApiOperation(value = "用户登录",notes = "前端要提交的参数名称：text登录的手机号或者邮箱，password是用户密码")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "text",value = "登录的手机号或者邮箱",required = true),
            @ApiImplicitParam(name = "password",value = "密码",required = true)
    })

    @ApiResponses(value = {
            @ApiResponse(code = 200,message = "登录成功"),
            @ApiResponse(code = 500,message = "登录失败")
    })
    public CommonResult login(String text, String password) throws Exception {

        if(text==null||password==null){
            return CommonResult.failed("账号或密码不能为空");
        }
        try {
            businessInfoService.login(text,password);
        } catch (LoginException e) {
            e.printStackTrace();
            return CommonResult.failed(e.getMessage());
        }
        return CommonResult.success("登录成功");
    }

    /**
     * 邮箱注册
     * @param user
     * @return
     */
    @PostMapping("/mailboxRegister")
    @ResponseBody

    public CommonResult mailboxRegister(BusinessInfo user){
        //1.搜索邮箱，邮箱不存在或邮箱状态不为0
        boolean flag=businessInfoService.queryMailbox(user.getMailbox());
        // 2.发送邮件，存储邮箱，并将mailbox_status状态改为1，并随机生成一个code邮箱令牌，并存储到数据库
        if(flag){
            try {
                businessInfoService.register(user);
                return CommonResult.success("邮件发送成功，请激活");
            } catch (Exception e) {
                e.printStackTrace();
                return CommonResult.failed("邮箱不正确");
            }
        }else{
            return CommonResult.failed("邮箱已被注册");
        }
    }

    /**
     * 验证码发送
     * @param phone 手机号码
     * @param resetCode 密码重置参数，1密码重置，短信登录，0注册
     * @return
     */
    @PostMapping("/phoneRegister")
    @ResponseBody
    @ApiOperation(value = "验证码发送",notes = "前端要提交的参数名称：phone是手机号码，resetCode是密码重置参数，1密码重置，短信登录，0注册")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "phone",value = "手机号码",required = true),
            @ApiImplicitParam(name = "resetCode",value = "密码重置参数，1密码重置，短信登录，0注册",required = false)
    })

    @ApiResponses(value = {
            @ApiResponse(code = 200,message = "验证码发送成功"),
            @ApiResponse(code = 500,message = "验证码发送失败")
    })
    public CommonResult phoneRegister(String phone,String resetCode){
        if (phone==null||phone.equals("")){
            return CommonResult.failed("请输入手机号");
        }

        try {
            businessInfoService.phoneRegister(phone,resetCode);
            return CommonResult.success("验证码发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(e.getMessage());
        }
    }

    /**
     * 验证码校正
     * @param phone 电话号码
     * @param code 验证码
     * @return
     */
    @PostMapping("/codeCheck")
    @ResponseBody
    @ApiOperation(value = "验证码校正",notes = "前端要提交的参数名称：phone是手机号码，code是验证码，password是用户密码")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "phone",value = "手机号码",required = true),
            @ApiImplicitParam(name = "code",value = "验证码",required = true),
            @ApiImplicitParam(name = "password",value = "密码",required = true)
    })

    @ApiResponses(value = {
            @ApiResponse(code = 200,message = "注册成功"),
            @ApiResponse(code = 500,message = "注册失败")
    })
    public CommonResult codeCheck(String phone,String code,String password){
        try {
            businessInfoService.codeCheck(code,phone);
            BusinessInfo info=new BusinessInfo();
            info.setStatus(0);
            info.setPassword(password);
            info.setCellPhNumber(phone);
            //进行账号和密码保存
            BusinessInfo businessInfo = businessInfoService.insert(info);
            return CommonResult.success("注册成功");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(e.getMessage());
        }
    }

    /**
     * 添加个人信息
     * @param user
     * @return
     */
    @PostMapping("/addInfo")
    @ResponseBody
    @ApiOperation(value = "添加个人信息",notes = "前端要提交的参数名称：user 是用户信息")
    @ApiResponses(value = {
            @ApiResponse(code = 200,message = "添加成功"),
            @ApiResponse(code = 500,message = "添加失败")
    })
    public CommonResult addInfo(@RequestBody BusinessInfo user){
        try {
            businessInfoService.updateByCellPhNumber(user);
            return CommonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }
    /**
     * 修改邮箱状态
     * @param code 邮箱的令牌
     * @return
     */
    @GetMapping("/activate")
    @ResponseBody

    public ModelAndView activate(String code){
        //激活邮箱
        ModelAndView mv=new ModelAndView();
        try {
            businessInfoService.updateMailboxStatus(code);
            mv.setViewName("mailboxRegisterMessage");
            return mv;
        }catch (MailboxStatusException e){
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 密码修改
     * @param cellPhNumber 手机号码
     * @param password 新密码
     * @return
     */
    @PostMapping("/resetPassword")
    @ApiOperation(value = "密码修改")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "cellPhNumber",value = "手机号码",required = true),
            @ApiImplicitParam(name = "password",value = "新密码",required = true)
    })

    @ApiResponses(value = {
            @ApiResponse(code = 200,message = "修改成功"),
            @ApiResponse(code = 500,message = "修改失败")
    })
    public CommonResult resetPasswordByPhone(String cellPhNumber,String password){
        if (password==null){
            return CommonResult.failed("密码不能为空");
        }
        try {
            businessInfoService.updatePasswordByCellPhNumber(cellPhNumber,password);
            return CommonResult.success("修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("修改失败");
        }
    }

    /**
     * 根据个人的id查询个人信息
     * @return
     */
    @GetMapping("/queruyPersonageInfo")
    @ApiOperation(value = "查询个人信息")
  public MyCenter queruyPersonageInfo(){
        String userId = request.getHeader("userId");
        Integer value = Integer.valueOf(userId);
        MyCenter myCenter=businessInfoService.queruyPersonageInfo(value);
        if (myCenter==null){
            myCenter=businessInfoService.queruyPersonageInfo2(value);
        }

        return myCenter;
  }
    /**
     * 根据个人的id查询商家拥有的订单数
     * @return
     */
    @GetMapping("/orderSum")
    @ApiOperation(value = "查询商家拥有的订单数")
  public MyCenter orderSum(){
        String userId = request.getHeader("userId");
        Integer value = Integer.valueOf(userId);
        MyCenter myCenter=businessInfoService.queruyOrderSum(value);
        if (myCenter==null){
            myCenter=new MyCenter();
            myCenter.setOrderSum(0);
        }
        return myCenter;
  }

    /**
     * 根据个人的id查询商家拥有的预订单数
     * @return
     */
    @GetMapping("/bookOrederSum")
    @ApiOperation(value = "查询商家拥有的预订单数")
    public MyCenter bookOrederSum(){
        String userId = request.getHeader("userId");
        Integer value = Integer.valueOf(userId);
        MyCenter myCenter=businessInfoService.bookOrederSum(value,0);
        if (myCenter==null){
            myCenter=new MyCenter();
            myCenter.setBookOrederSum(0);
        }
        return myCenter;
    }

    /**
     * 根据登录的商家查询其个人信息
     * @return
     */
    @GetMapping("/queryByUserId")
    @ApiOperation(value = "查询商家查询其个人信息")
    public BusinessInfoAreainfo queryByUserId(){
        String userId = request.getHeader("userId");
        Integer value = Integer.valueOf(userId);
        BusinessInfoAreainfo infoareainfo=new BusinessInfoAreainfo();
        BusinessInfo businessInfo=businessInfoService.queryById(value);
        Areainfo areainfo=areainfoService.queryById(businessInfo.getPlotId());
        infoareainfo.setBusinessInfo(businessInfo);
        infoareainfo.setAreainfo(areainfo);
        return infoareainfo;
    }

    @GetMapping("/noteSubLogin")
    @ApiOperation(value = "查询商家个人信息")
    public BusinessInfoAreainfo noteSubLogin( ){
        String userId = request.getHeader("userId");
        Integer value = Integer.valueOf(userId);
        BusinessInfoAreainfo infoareainfo=new BusinessInfoAreainfo();
        BusinessInfo businessInfo=businessInfoService.queryById(value);
        Areainfo areainfo=areainfoService.queryById(businessInfo.getPlotId());
        infoareainfo.setBusinessInfo(businessInfo);
        infoareainfo.setAreainfo(areainfo);
        return infoareainfo;
    }


    /**
     * 短信登录
     * @param phone 电话号码
     * @param code 验证码
     * @return
     */
    @PostMapping("/noteLogn")
    @ResponseBody
    @ApiOperation(value = "短信登录")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "phone",value = "电话号码",required = true),
            @ApiImplicitParam(name = "code",value = "验证码",required = true)
    })

    @ApiResponses(value = {
            @ApiResponse(code = 200,message = "登录成功"),
            @ApiResponse(code = 500,message = "登录失败")
    })
    public CommonResult noteLogn(String phone,String code){

        try {
            businessInfoService.codeCheck(code,phone);
            BusinessInfo businessInfo= businessInfoService.queryByPhone(phone);
            if(businessInfo==null){
                return CommonResult.failed("账号未注册，请先注册");
            }
            System.out.println("businessInfo"+businessInfo);
            LoginToken loginToken=new LoginToken();
            loginToken.setUserId(businessInfo.getId());
            loginToken.setUsername(businessInfo.getName());
            return CommonResult.success("登录成功",loginToken);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(e.getMessage());
        }
    }

    /**
     * 查询收益
     * @param userId 根据用户id
     * @return
     */
    @GetMapping("/queryIncome")
    @ApiOperation(value = "查询收益")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "userId",value = "用户id",required = true),
    })
    public String queryIncome(Integer userId){
        String money=businessInfoService.queryIncome(userId);
        if(money==null||money.equals("0")){
            money="0";
        }
        return money;
    }

    /**
     * 根据用户的id修改昵称
     * @param info 用户信息
     * @return
     */
    @RequestMapping("/alterUserInfo")
    @ApiOperation(value = "根据用户的id修改昵称")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "areaAddress",value = "小区地址",required = true)
    })

    @ApiResponses(value = {
            @ApiResponse(code = 200,message = "修改成功"),
            @ApiResponse(code = 500,message = "修改失败")
    })
    public CommonResult alterUserInfo(BusinessInfo info,String areaAddress){
          if(info.getId()==null){
              return CommonResult.failed("用户未登录");
          }

        try {
            businessInfoService.update(info);
            if(areaAddress!=null&&!areaAddress.equals("")){
                BusinessInfo info1 = businessInfoService.queryById(info.getId());
                if(info1.getPlotId()!=null&&!info1.getPlotId().equals("")){
                    Areainfo areainfo=new Areainfo();
                    areainfo.setAreaAddress(areaAddress);
                    areainfo.setId(info1.getId());
                    //修改数据
                    areainfoService.update(areainfo);
                }else{
                    //插入一条新数据
                    Areainfo areainfo=new Areainfo();
                    areainfo.setAreaAddress(areaAddress);
                    areainfoService.insert(areainfo);
                }
            }
            return CommonResult.success("修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("修改失败");
        }
    }


    /**
     * 修改手机号
     * @param phone 电话号码
     * @param code 验证码
     * @param userId 用户id
     * @return
     */
    @PostMapping("/alterPhone")
    @ResponseBody
    @ApiOperation(value = "修改手机号")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "phone",value = "手机号码",required = true),
            @ApiImplicitParam(name = "code",value = "验证码",required = true),
            @ApiImplicitParam(name = "userId",value = "用户id",required = true)
    })

    @ApiResponses(value = {
            @ApiResponse(code = 200,message = "修改成功"),
            @ApiResponse(code = 500,message = "修改失败")
    })
    public CommonResult alterPhone(String phone,String code,Integer userId){
              if(userId==null||userId.equals("")){
                  return CommonResult.failed("用户未登录");
              }
        try {
            businessInfoService.codeCheck(code,phone);
            BusinessInfo info=new BusinessInfo();
            info.setCellPhNumber(phone);
            info.setId(userId);
            businessInfoService.update(info);
            return CommonResult.success("修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(e.getMessage());
        }
    }
}